package impl

import (
	"context"
	"deployment-service/domain"
	"deployment-service/jenkins"
	"github.com/bndr/gojenkins"
)

type jobAdapter struct {
	ctx     context.Context
	jenkins *gojenkins.Jenkins
	job     *gojenkins.Job
}

func (m jobAdapter) Build(params map[string]string) (int64, error) {
	return m.jenkins.BuildJob(
		m.ctx,
		m.job.GetName(),
		params,
	)
}

func (m jobAdapter) GetBuildFromQueueID(queueID int64) (jenkins.IJenkinsBuild, error) {
	build, err := m.jenkins.GetBuildFromQueueID(m.ctx, queueID)
	if err != nil {
		return nil, err
	}

	return buildAdapter{
		ctx: m.ctx,
		build: build,
	}, nil
}

func (m jobAdapter) GetConfig() (string, error) {
	return m.job.GetConfig(m.ctx)
}

func (m jobAdapter) GetLastBuild() (jenkins.IJenkinsBuild, error) {
	build, err := m.job.GetLastBuild(m.ctx)
	if err != nil {
		return nil, err
	}

	return &buildAdapter{
		build: build,
	}, nil
}

func NewJenkins(jenkinsEntity *domain.JenkinsEntity) jenkins.IJenkins {
	ctx := context.Background()
	return &jenkinsAdapter{
		ctx:     ctx,
		jenkins: getGOJenkins(ctx, *jenkinsEntity),
	}
}